const jwt = require('jsonwebtoken')


function sign(option) {
    return jwt.sign(option, 'kfc', {
        expiresIn: 86400
    }) // 加盐
}

// 校验
function verify() {
    return async (ctx, next) => {
        const jwtToken = ctx.req.headers.authorization
        // console.log(jwtToken);
        if (jwtToken) {
            try {
                // console.log(123123);
                const decoded = jwt.verify(jwtToken, 'kfc')
                // console.log(decoded);
                if (decoded.id) {
                    ctx.userId = decoded.id
                    ctx.nickname = decoded.nickname
                    await next()
                }
            } catch (error) {
                ctx.body = {
                    // status: 401,
                    code: 811,
                    msg: 'Token失效'
                }
            }
        } else {
            ctx.body = {
                code: 810,
                msg: 'Token不能为空'
            }
        }

    }
}

const TokenId = (token,str)=>{
    const decoded = jwt.verify(token, str)
    return decoded.id;
}

module.exports = {
    sign,
    verify,
    TokenId
}